<?php
namespace app\index\controller;

use app\index\model\User as UserModel;
use app\index\model\Setting;
use think\facade\View;
use think\facade\Session;
use think\captcha\facade\Captcha;
use hema\wechat\Driver;

/**
 * 用户认证
 */
class Passport extends Controller
{
    /**
     * 生成验证码
     **/
    public function captcha()
    {
        return Captcha::create();
    }

    /**
     * 用户登录
     */
    public function login()
    {
        if (!$this->request->isAjax()) {
            // 验证登录状态
            if (isset($this->user) AND (int)$this->user['is_login'] === 1) {
                return redirect('/user');
            }
            $values = Setting::getItem('wxweb',0);
            View::assign('app_id', $values['app_id']);
            View::assign('key', 'user');
            View::assign('title', '用户登录');
            View::assign('description', '');
            View::assign('keywords', '');
            return View::fetch();
        }
        $model = new UserModel;
        if (($model->login($this->postData('data'))) === false) {
            return $this->renderError($model->getError() ?: '登录失败');
        }
        return $this->renderSuccess('登录成功', '/user');
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        // 清空登录状态
        Session::delete('hema_user');
        return redirect('/');
    }
    
    /**
     * 微信扫码登录
     */
    public function wxlogin(string $code = '',$state = 0)
    {
    	$wx = new Driver;
    	//通过code获取access_token
        if(!$result = $wx->getWebToken($code)){
	    	die(hema_json(['code' => 0, 'msg' => $wx->getError()]));
	    }
	    //获取用户信息
        if(!$result = $wx->getUserinfo($result['openid'],$result['access_token'])){
            die(hema_json(['code' => 0, 'msg' => $wx->getError()]));
        }
        if(!$user = UserModel::where('union_id',$result['unionid'])->where('status','>',10)->find()){
			$user = new UserModel;
			$user->save([
        		'union_id' => $result['unionid'],
				'nickname' => preg_replace('/[\xf0-\xf7].{3}/', '', $result['nickname']),
				'avatar' => $result['headimgurl'],
				'gender' => $result['sex'],
				'country' => $result['country'],
				'province' => $result['province'],
				'city' => $result['city'],
				'user_name' => time(),
				'password' => hema_hash('123456'),
				'status' => 20, //商户管理
			]);
			$user = UserModel::where('union_id',$result['unionid'])->where('status','>',10)->find();
		}else{
			//如果之前没有生成账号和密码，这里重新生成
			if(empty($user['user_name'])){
				$user->save([
					'user_name' => time(),
					'password' => hema_hash('123456')
				]);
			}
		}
		// 保存登录状态
		Session::set('hema_user', [
			'user' => $user,
			'is_login' => true,
		]);
		return redirect('/user');
	}
}
